package com.panda.expand;

import com.panda.pojo.Context;
import com.panda.pojo.Element;
import com.panda.utils.Finder;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NgBindBodyParser implements BodyParser {


    private static Pattern pattern = Pattern.compile("\\.[\n ]*ng-([a-zA-Z][a-zA-Z0-9]*)");

    @Override
    public String parseBody(Context context, Element element, String s) {


        Matcher matcher = pattern.matcher(s);

        String to = s;

        while (matcher.find()) {

            String name = matcher.group(1);

            int end = Finder.findBody(s.toCharArray(), matcher.end());

            if (end == -1) {

                int l = s.length();

                int e = l - matcher.start() > 20 ? matcher.start() + 19 : l;

                throw new RuntimeException("处理ng-事件绑定时格式错误:" + matcher.group() + "\n" + s.substring(matcher.start(), e));
            }

            String pb = s.substring(matcher.end(), end).trim();


            String p;

            String b;

            if (pb.startsWith("{")) {
                p = "()";
                b = pb;
            } else if (pb.startsWith("(")) {
                int pn = Finder.findParam(pb.toCharArray(), 0);

                p = pb.substring(0, pn);

                b = pb.substring(pn);

            } else {

                int l = s.length();

                int e = l - matcher.start() > 20 ? matcher.start() + 19 : l;

                throw new RuntimeException("处理ng-事件绑定时格式错误:" + matcher.group() + "\n" + s.substring(matcher.start(), e));
            }


            String r = s.substring(matcher.start(), end);

            String t = "." + name + "(function" + p + "{\n$scope.$apply(function()" + b + "\n)})";

             to = to.replace(r, t);

        }

        return to;
    }


}
/*
            if (el.equals(element.getId())) {
                s = "\nif (!" + el + ".attr('" + command + "')) {$compile(" + el + ".attr('" + command + "', '" + body + "'))($scope.$parent);return;}\n\n\n" + s.replace(r, "");
            } else {
                s = "\nif (!" + el + ".attr('" + command + "')) {$compile(" + el + ".attr('" + command + "', '" + body + "'))($scope);}\n\n\n" + s.replace(r, "");
            }
*/
